package com.le.tester.book.effectivejava3rdchinese.secondReading.l10;

import java.util.Objects;

/**
 * createTime：2024-08-15 9:36
 * description：字符串忽略大小写判断是否相等
 */
public class CaseInsensitiveString implements Comparable<CaseInsensitiveString> {
    private final String s;

    public CaseInsensitiveString(String s) {
        this.s = Objects.requireNonNull(s);
    }

    @Override
    public boolean equals(Object obj) {
        //违反了对称性
//        if (obj instanceof CaseInsensitiveString) {
//            return s.equalsIgnoreCase(((CaseInsensitiveString) obj).s);
//        }
//
//        if (obj instanceof String) {
//            return s.equalsIgnoreCase((String) obj);
//        }
//        return false;

        return obj instanceof CaseInsensitiveString && (((CaseInsensitiveString) obj).s.equalsIgnoreCase(s));
    }

    public static void main(String[] args) {
        CaseInsensitiveString cis = new CaseInsensitiveString("Polish");
        String s = "polish";
        System.out.println(cis.equals(s)); // true
        //并没用调用重写的equals方法
        System.out.println(s.equals(cis)); // false
    }

    @Override
    public int compareTo(CaseInsensitiveString o) {
        return String.CASE_INSENSITIVE_ORDER.compare(s,o.s);
    }
}
